from flask import Flask, request, redirect, url_for, render_template, session, flash
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = 'your_very_secret_key_here'  # 生产环境请使用更安全的密钥

# 模拟数据库（实际项目请使用真实数据库）
users_db = {
    "user1": {
        "password": generate_password_hash("password123"),
        "id": 1
    }
}

# 主页（自动跳转）
@app.route('/')
def home():
    if 'username' in session:
        return redirect(url_for('welcome'))
    return redirect(url_for('login_page'))

# 登录页面
@app.route('/login', methods=['GET'])
def login_page():
    return render_template('login.html')

# 登录处理
@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    
    user = users_db.get(username)
    
    if user and check_password_hash(user['password'], password):
        session['username'] = username
        return redirect(url_for('welcome'))
    
    flash('用户名或密码错误', 'error')
    return redirect(url_for('login_page'))

# 注册页面
@app.route('/register', methods=['GET'])
def register_page():
    return render_template('register.html')

# 注册处理
@app.route('/register', methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    confirm_password = request.form.get('confirm_password')
    
    # 验证输入
    if not username or not password:
        flash('用户名和密码不能为空', 'error')
        return redirect(url_for('register_page'))
    
    if password != confirm_password:
        flash('两次输入的密码不一致', 'error')
        return redirect(url_for('register_page'))
    
    if username in users_db:
        flash('用户名已存在', 'error')
        return redirect(url_for('register_page'))
    
    # 创建用户
    users_db[username] = {
        "password": generate_password_hash(password),
        "id": len(users_db) + 1
    }
    
    flash('注册成功，请登录', 'success')
    return redirect(url_for('login_page'))

# 欢迎页
@app.route('/welcome')
def welcome():
    if 'username' not in session:
        return redirect(url_for('login_page'))
    return render_template('welcome.html', username=session['username'])

# 退出登录
@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('login_page'))

if __name__ == '__main__':
    app.run(debug=True, port=5000)